
package com.lmx.persistence.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.lmx.common.util.CommonUtil;
import com.lmx.repoDomain.tmodel.Account;
import com.lmx.repoDomain.tmodel.Dicttype;
import com.lmx.repoDomain.tmodel.ImsPool;
import com.lmx.repoDomain.tmodel.Task;
import com.lmx.repoDomain.tmodel.TaskExtend;
import com.lmx.repoDomain.tmodel.UserTask;
import com.lmx.repoDomain.tmodel.Worktime;
//import com.lmx.repoDomain.model.*;
import com.lmx.repoDomain.tmodel.business.User;//huibati
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;


/**
 * #{description}
 *
 * @author Administrator
 * @version 1.00
 */
@Service
@Scope("prototype")
public class TaskService<T>{
    private Log logger = LogFactory.getLog(this.getClass());

    @PersistenceContext
    private EntityManager em;
    
    @Autowired
    protected GenericService dslJpaService;
    
    @Autowired
    protected DataProcessService dataProcessService;

	@Autowired
	private HuaweiService huaweiService;

    /**
     * 获取企业任务列表
     * @param values
     * @return
     */
    public List<Map<String ,Object>> getTaskList(Map<String ,Object> values){
    	
		logger.debug("获取企业任务列表");
		
		List<Map<String ,Object>> taskList = new ArrayList<Map<String ,Object>>();
		
		String query = "select t from Task t where 1=1 and t.delStatus != '1'";
		//任务名称
		String title = (String)values.get("title");
		if(title != null && !title.isEmpty()){
			query = query + " and t.title like '%"+title+"%'";
		}
		//企业名称
		String entName = (String)values.get("entName");
		if(entName != null && !entName.isEmpty()){
			query = query + " and t.pubuser.entName like '%"+entName+"%'";
		}
		//任务呼叫类型
		String callType = (String)values.get("callType");
		if(callType != null && !callType.isEmpty()){
			query = query + " and t.callType = "+callType;
		}
		//进行状态
		String runstatus = (String)values.get("runstatus");
		if(runstatus != null && !runstatus.isEmpty()){
			query = query + " and t.runstatus = "+runstatus;
		}
		//任务状态
		String status = (String)values.get("status");
		if(status != null && !status.isEmpty()){
			query = query + " and t.status.id = "+Long.valueOf(status);
		}
		
		query = query +" order by t.createTime desc";
		//获取企业任务列表
		Query qu = this.em.createQuery(query);
		qu.setMaxResults((int)values.get("size"));
		qu.setFirstResult((int)values.get("pageNum"));
		List resultList = qu.getResultList();
		
		for(int i = 0 ; i < resultList.size() ; i ++){
			Task task = (Task) resultList.get(i);
			Map<String ,Object> taskMap = new HashMap<String, Object>();
			
			Long taskID = task.getId();
			taskMap.put("taskID", taskID.toString());//任务id
			String titleStr = task.getTitle();
			taskMap.put("title", titleStr==null?titleStr="":titleStr);//任务名称
			String entNameStr = "";
			String loginName = "";
			Double balance = 0.0;
			User user = task.getPubuser();
			if(user != null){
				entNameStr = user.getEntName();
				loginName = user.getLoginName();
				//用户账户信息
				List result = this.em.createQuery("select a from Account a where a.user.id = ?1")
						.setParameter(1, user.getId())
						.getResultList();
				
				if(result.size()>0){
					Account account = (Account) result.get(0);
					balance = account.getBalance();
				}
			}
			taskMap.put("balance", balance==null?balance=0.0:balance);//企业账户余额
			taskMap.put("entName", entNameStr==null?entNameStr="":entNameStr);//企业名称
			taskMap.put("loginName", loginName==null?loginName="":loginName);//发布企业
			Short callTypeSh = task.getCallType();
			taskMap.put("callType", callTypeSh==null?callTypeSh=0:callTypeSh);//任务呼叫类型
			String desc = task.getDesc();
			taskMap.put("desc", desc==null?desc="":desc);//任务描述
			Double onlinePay = task.getOnlinePay();
			taskMap.put("onlinePay", onlinePay==null?onlinePay=0.0:onlinePay);//在线时长报酬
			Double callinPay = task.getCallinPay();
			taskMap.put("callinPay", callinPay==null?callinPay=0.0:callinPay);//接听报酬
			Double calloutPay = task.getCalloutPay();
			taskMap.put("calloutPay", calloutPay==null?calloutPay=0.0:calloutPay);//外呼报酬
			Double poPay = task.getPoPay();
			taskMap.put("poPay", poPay==null?poPay=0.0:poPay);//成单报酬
			String statusStr = "";
			Dicttype dicttype = task.getStatus();
			if(dicttype != null){
				statusStr = dicttype.getTypename();
			}
			taskMap.put("status", statusStr==null?statusStr="":statusStr);//任务状态
			Short runstatusSh = task.getRunstatus();
			taskMap.put("runstatus", runstatusSh==null?runstatusSh=2:runstatusSh);//进行状态
			String createTime = "";
			Integer createTimeInt =  task.getCreateTime();
			if(createTimeInt != null){
				createTime = CommonUtil.integetTimeForString(createTimeInt);
			}
			taskMap.put("createTime", createTime);//创建时间
			String updateTime = "";
			Integer updateTimeInt =  task.getUpdateTime();
			if(updateTimeInt != null){
				updateTime = CommonUtil.integetTimeForString(updateTimeInt);
			}
			taskMap.put("updateTime",updateTime);//修改时间
			Double money = 0.0;
			Integer csNeed = 0;
			Integer csHave = 0;
			TaskExtend taskExtend = task.getExtendIfo();
			if(taskExtend != null){
				money = taskExtend.getMoney();
				csNeed = taskExtend.getCsNeed();
				csHave = taskExtend.getCsHave();
			}
			taskMap.put("money", money==null?money=0.0:money);//任务使用金额
			taskMap.put("csNeed", csNeed==null?csNeed=0:csNeed);//需要客服数量
			taskMap.put("csHave", csHave==null?csHave=0:csHave);//已招客服数量
			
			taskList.add(taskMap);
		}
		
        return taskList;
    }
    
    /**
     * 获取任务列表总条数
     * @param values
     * @return
     */
    public int getTaskListCount(Map<String ,Object> values){
    	
		logger.debug("获取任务列表总条数");
		
		String query = "select count(t.id) from Task t where 1=1 and t.delStatus != '1'";
		//任务名称
		String title = (String)values.get("title");
		if(title != null && !title.isEmpty()){
			query = query + " and t.title like '%"+title+"%'";
		}
		//企业名称
		String entName = (String)values.get("entName");
		if(entName != null && !entName.isEmpty()){
			query = query + " and t.pubuser.entName like '%"+entName+"%'";
		}
		//任务呼叫类型
		String callType = (String)values.get("callType");
		if(callType != null && !callType.isEmpty()){
			query = query + " and t.callType = "+callType;
		}
		//进行状态
		String runstatus = (String)values.get("runstatus");
		if(runstatus != null && !runstatus.isEmpty()){
			query = query + " and t.runstatus = "+runstatus;
		}
		//任务状态
		String status = (String)values.get("status");
		if(status != null && !status.isEmpty()){
			query = query + " and t.status.id = "+Long.valueOf(status);
		}
		int count = (int)(long)this.em.createQuery(query)
    			.getSingleResult();
		
        return count;
    }
    
    /**
     * 获取任务详情
     * @param taskID
     * @return
     */
    /*public Map<String ,Object> getTask(long taskID){
    	
		logger.debug("获取企业任务详情，任务id："+taskID);
		
		Map<String ,Object> taskMap = new HashMap<String, Object>();
		
		Task task = this.em.find(Task.class, taskID);
		
		taskMap.put("taskID", task.getId().toString());//任务id
		String explicitApplyFile = task.getExplicitApplyFile();
		taskMap.put("explicitApplyFile", explicitApplyFile==null?explicitApplyFile="":explicitApplyFile);//外显号码申请材料路径
		String taskCode = task.getCode();
		taskMap.put("taskCode", taskCode==null?taskCode="":taskCode);//任务code
		String titleStr = task.getTitle();
		taskMap.put("title", titleStr==null?titleStr="":titleStr);//任务名称
		String entNameStr = "";
		String loginName = "";
		Double balance = 0.0;
		User user = task.getPubuser();
		if(user != null){
			entNameStr = user.getEntName();
			loginName = user.getLoginName();
			//用户账户信息
			List result = this.em.createQuery("select a from Account a where a.user.id = ?1")
					.setParameter(1, user.getId())
					.getResultList();
			
			if(result.size()>0){
				Account account = (Account) result.get(0);
				balance = account.getBalance();
			}
		}
		taskMap.put("balance", balance==null?balance=0.0:balance);//企业账户余额
		taskMap.put("entName", entNameStr==null?entNameStr="":entNameStr);//企业名称
		taskMap.put("loginName", loginName==null?loginName="":loginName);//发布企业
		Short callTypeSh = task.getCallType();
		taskMap.put("callType", callTypeSh==null?callTypeSh=0:callTypeSh);//任务呼叫类型
		Short durType = task.getDurType();
		taskMap.put("durType", durType==null?durType=0:durType);//任务时间类型
		String desc = task.getDesc();
		taskMap.put("desc", desc==null?desc="":desc);//任务描述
		Double onlinePay = task.getOnlinePay();
		taskMap.put("onlinePay", onlinePay==null?onlinePay=0.0:onlinePay);//在线时长报酬
		Double callinPay = task.getCallinPay();
		taskMap.put("callinPay", callinPay==null?callinPay=0.0:callinPay);//接听报酬
		Double calloutPay = task.getCalloutPay();
		taskMap.put("calloutPay", calloutPay==null?calloutPay=0.0:calloutPay);//外呼报酬
		Double poPay = task.getPoPay();
		taskMap.put("poPay", poPay==null?poPay=0.0:poPay);//成单报酬
		String statusStr = "";
		Long statusID = (long) 0;
		Dicttype dicttype = task.getStatus();
		if(dicttype != null){
			statusStr = dicttype.getTypename();
			statusID = dicttype.getId();
		}
		taskMap.put("status", statusStr==null?statusStr="":statusStr);//任务状态
		taskMap.put("statusID", statusID==null?statusID=(long) 0:statusID);//任务状态id
		Short runstatusSh = task.getRunstatus();
		taskMap.put("runstatus", runstatusSh==null?runstatusSh=2:runstatusSh);//进行状态
		String createTime = "";
		Integer createTimeInt =  task.getCreateTime();
		if(createTimeInt != null){
			createTime = CommonUtil.integetTimeForString(createTimeInt);
		}
		taskMap.put("createTime", createTime);//创建时间
		String updateTime = "";
		Integer updateTimeInt =  task.getUpdateTime();
		if(updateTimeInt != null){
			updateTime = CommonUtil.integetTimeForString(updateTimeInt);
		}
		taskMap.put("updateTime",updateTime);//修改时间
		String verifyFailReason = task.getVerifyFailReason();
		taskMap.put("verifyFailReason", verifyFailReason==null?verifyFailReason="":verifyFailReason);//审核失败原因
		String beginTime = "";
		Integer beginTimeInt =  task.getBeginTime();
		if(beginTimeInt != null){
			beginTime = CommonUtil.integetTimeForString(beginTimeInt);
		}
		taskMap.put("beginTime", beginTime);//创建时间
		String endTime = "";
		Integer endTimeInt =  task.getEndTime();
		if(endTimeInt != null){
			endTime = CommonUtil.integetTimeForString(endTimeInt);
		}
		taskMap.put("endTime",endTime);//修改时间
		Double money = 0.0;
		Integer csNeed = 0;
		Integer csHave = 0;
		Integer calloutNum = 0;
	    Integer callinNum= 0;
	    String callinAveDuration= "";
	    String calloutAveDuration= "";
		TaskExtend taskExtend = task.getExtendIfo();
		if(taskExtend != null){
			money = taskExtend.getMoney();
			csNeed = taskExtend.getCsNeed();
			csHave = taskExtend.getCsHave();
			calloutNum = taskExtend.getCalloutNum();
		    callinNum= taskExtend.getCallinNum();
		    Integer callinAveDurationInt = taskExtend.getCallinAveDuration();
		    if(callinAveDurationInt != null){
		    	callinAveDuration= CommonUtil.timeChange(callinAveDurationInt);
		    }
		    Integer calloutAveDurationInt = taskExtend.getCalloutAveDuration();
		    if(calloutAveDurationInt != null){
		    	calloutAveDuration= CommonUtil.timeChange(calloutAveDurationInt);
		    }
		}
		taskMap.put("money", money==null?money=0.0:money);//任务使用金额
		taskMap.put("csNeed", csNeed==null?csNeed=0:csNeed);//需要客服数量
		taskMap.put("csHave", csHave==null?csHave=0:csHave);//已招客服数量
		taskMap.put("calloutNum", calloutNum==null?calloutNum=0:calloutNum);//全部外呼数量
		taskMap.put("callinNum", callinNum==null?callinNum=0:callinNum);//全部内呼数量
		taskMap.put("callinAveDuration", callinAveDuration==null?callinAveDuration="":callinAveDuration);//呼入平均时长
		taskMap.put("calloutAveDuration", calloutAveDuration==null?calloutAveDuration="":calloutAveDuration);//呼出平均时长
		
		String ims = "";
		String imsPasswd = "";
		ImsPool imsPool = task.getImsPool();//总机号码
		if(imsPool != null){
			ims = imsPool.getIms();
			imsPasswd = imsPool.getImsPasswd();
		}
		taskMap.put("ims", ims==null?ims="":ims);//总机号码
		taskMap.put("imsPasswd", imsPasswd==null?imsPasswd="":imsPasswd);//总机密码
		
		String settleAccountWayStr = "";
		Short settleAccountWay = task.getSettleAccountWay();
		if(settleAccountWay != null){
			settleAccountWayStr = ICommonConstants.SETTLEACCOUNTWAY.values()[settleAccountWay].label();
		}
		taskMap.put("settleAccountWayStr", settleAccountWayStr==null?settleAccountWayStr="":settleAccountWayStr);//结算方式
		
		//当前任务客服信息
		List<Map<String ,Object>> userList = new ArrayList<Map<String ,Object>>();
		List resultList = this.em.createQuery("select u from User u ,UserTask ut where u.id = ut.user.id and ut.task.id = ?1")
				.setParameter(1, taskID)
				.getResultList();
		for(int i=0;i<resultList.size();i++){
			User user1 = (User)resultList.get(i);
			Map<String ,Object> userMap = new HashMap<String, Object>();
			String nameStr = user1.getName();
			userMap.put("name", nameStr==null?nameStr="":nameStr);//姓名
			String phoneStr = user1.getStaffTel();
			userMap.put("phone", phoneStr==null?phoneStr="":phoneStr);//手机号码
//			Short sexNum = user1.getSex();
//			String sex = "";
//			if(sexNum != null){
//				sex = ICommonConstants.GENDER.values()[sexNum].label();
//			}
//			userMap.put("sex", sex);//性别
			String language = "";
			Set<Dicttype> dictTypeSetL = (Set<Dicttype>) user1.getLanguage();
			if(dictTypeSetL.size()>0){
				for(Dicttype dictType : dictTypeSetL){
					language = dictType.getTypename() + ";" + language;
				}
			}
			String cstag = "";
			Set<Dicttype> dictTypeSetC = (Set<Dicttype>) user1.getCstag();
			if(dictTypeSetC.size()>0){
				for(Dicttype dictType : dictTypeSetC){
					cstag = dictType.getTypename() + "  " + cstag;
				}
			}
			userMap.put("language", language);//语种
			userMap.put("cstag", cstag);//标签、擅长
			
			//好评率
			Integer rate = 0 ;
			//经验值
			Integer workHour = 0 ;
			//等级
			String level = "";
			
			Userextend userExtend = user.getExtendInfo();
			if(userExtend != null){
				rate = userExtend.getRate();
				workHour = userExtend.getWorkHour();
				Dicttype dictType = userExtend.getLevel();
				if(dictType != null){
					level = dictType.getTypename();
				}
			}
			userMap.put("rate", rate==null?rate=0:rate);//信誉（好评率）
			userMap.put("workHour", workHour==null?workHour=0:workHour);//经验值
			userMap.put("level", level==null?level="":level);//等级
			
			userList.add(userMap);
		}
		taskMap.put("userList", userList);
		//当前任务工作时间
		List<Map<String ,Object>> workTimeList = new ArrayList<Map<String ,Object>>();
		Set<Worktime> worktimes = task.getWorktimes();
		if(worktimes.size()>0){
			for(Worktime taskWorkTime : worktimes){
				Map<String ,Object> workTimeMap = new HashMap<String, Object>();
				workTimeMap.put("beginHour", taskWorkTime.getBeginHour()+":00");
				workTimeMap.put("endHour", taskWorkTime.getEndHour()+":00");
				workTimeMap.put("section", taskWorkTime.getSection());
				workTimeMap.put("remark", taskWorkTime.getRemark());
				
				workTimeList.add(workTimeMap);
			}
		}
		taskMap.put("workTimeList", workTimeList);
		//任务分类
		String taskTypes = "";
		Set<Dicttype> taskTypesSet = task.getTaskTypes();
		if(taskTypesSet.size()>0){
			for(Dicttype sictType : taskTypesSet){
				String taskTypes1 = sictType.getTypename();
				taskTypes = taskTypes + " " + taskTypes1;
			}
		}
		taskMap.put("taskTypes", taskTypes);
		
        return taskMap;
    }
   */ 
    /**
     * 修改任务状态
     * @return
     */
    @Transactional
    public void updateTaskStatus(Task task){
    	
		logger.debug("修改任务状态");
		
		long statusID = task.getStatus().getId();
		String runstatus = "";//进行状态  0，未开始  1已开始
		String verifyFailReason = task.getVerifyFailReason();
		task = this.em.find(Task.class, task.getId());
		Integer beginTime = task.getBeginTime();// 开始时间
	    Integer endTime = task.getEndTime();// 结束时间
	    //系统当前时间
	    Integer time = CommonUtil.getCurrTimes();
	    if(statusID == 8){
	    	 if(beginTime != null && time>=beginTime){//如果当前时间大于开始时间，任务已开始
	 	    	statusID = 10;
	 	    	//当前任务工作时间
	 			Set<Worktime> worktimes = task.getWorktimes();
	 			if(worktimes.size()>0){
	 				for(Worktime taskWorkTime : worktimes){
	 					Integer beginHour = taskWorkTime.getBeginHour();
	 					Integer endHour = taskWorkTime.getEndHour();
	 					if(CommonUtil.getDayHoure(beginHour)<=time && time<=CommonUtil.getDayHoure(endHour)){
	 						runstatus = "1";
	 						task.setRunstatus(Short.valueOf(runstatus));
	 					}
	 				}
	 			}
	 	    }else if(endTime != null && time>=endTime){//如果当前时间大于结束时间，任务已结束
	 	    	statusID = 11;
	 	    }
	    }
	    
	    task.setVerifyFailReason(verifyFailReason);
	    Dicttype status = this.em.find(Dicttype.class, statusID);
	    task.setStatus(status);
	    
		//修改任务状态
	    dslJpaService.setEntityClass(Task.class);
	    dslJpaService.update(task);
    }
    
    /**
     * 获取客服任务列表
     * @param values
     * @return
     */
    public List<Map<String ,Object>> getUserTaskList(Map<String ,Object> values){
    	
		logger.debug("获取客服任务列表");
		
		List<Map<String ,Object>> userTaskList = new ArrayList<Map<String ,Object>>();
		
		String query = "select ut from UserTask ut where 1=1 and ut.delStatus != '1'";
		
		//用户名
		String loginName = (String)values.get("loginName");
		if(loginName != null && !loginName.isEmpty()){
			query = query + " and ut.user.loginName like '%"+loginName+"%'";
		}
		//客服名称
		String name = (String)values.get("name");
		if(name != null && !name.isEmpty()){
			query = query + " and ut.user.name like '%"+name+"%'";
		}
		//任务名称
		String taskName = (String)values.get("taskName");
		if(taskName != null && !taskName.isEmpty()){
			query = query + " and ut.task.title like '%"+taskName+"%'";
		}
		//绑定手机号
		String bindPhone = (String)values.get("bindPhone");
		if(bindPhone != null && !bindPhone.isEmpty()){
			query = query + " and ut.bindPhone like '%"+bindPhone+"%'";
		}
		
		//状态
		String statusStr = (String)values.get("status");
		if(statusStr != null && !statusStr.isEmpty()){
			query = query + " and ut.status.id = "+statusStr;
		}
		//坐席号
		String phoneNumber = (String)values.get("phoneNumber");
		if(phoneNumber != null && !phoneNumber.isEmpty()){
			query = query + " and ut.phoneNumber like '%"+phoneNumber+"%'";
		}
		//操作员账号
		String agentNumber = (String)values.get("agentNumber");
		if(agentNumber != null && !agentNumber.isEmpty()){
			query = query + " and ut.agentNumber like '%"+agentNumber+"%'";
		}		
		query = query +" order by ut.createTime desc";
		//获取客服列表
		Query qu = this.em.createQuery(query);
		qu.setMaxResults((int)values.get("size"));
		qu.setFirstResult((int)values.get("pageNum"));
		List resultList = qu.getResultList();
		
		for(int i = 0 ; i < resultList.size() ; i ++){
			UserTask userTask = (UserTask) resultList.get(i);
			Map<String ,Object> userTaskMap = new HashMap<String, Object>();
			
			Long userTaskID = userTask.getId();
			userTaskMap.put("userTaskID", userTaskID.toString());//任务id
			
			String loginNameStr = "";
			String nameStr = "";
			User user = userTask.getUser();
			if(user != null){
				loginNameStr = user.getLoginName();
				nameStr = user.getName();
			}
			userTaskMap.put("loginName", loginNameStr==null?loginNameStr="":loginNameStr);//用户名
			userTaskMap.put("name", nameStr==null?nameStr="":nameStr);//姓名
			String bindPhoneStr = userTask.getBindPhone();
			userTaskMap.put("bindPhone", bindPhoneStr==null?bindPhoneStr="":bindPhoneStr);//绑定手机号
			String title = "";
			String desc = "";
			Task task = userTask.getTask();
			if(task != null){
				title = task.getTitle();
				desc = task.getDesc();
			}
			userTaskMap.put("title", title==null?title="":title);//任务名称
			userTaskMap.put("desc", desc==null?desc="":desc);//任务描述
			String effectiveTime = "";
			Integer effectiveTimeInt =  userTask.getEffectiveTime();
			if(effectiveTimeInt != null){
				effectiveTime = CommonUtil.integetTimeForString(effectiveTimeInt);
			}
			userTaskMap.put("effectiveTime", effectiveTime);//任务生效时间
			String status = "";
			String statusID = "";
			Dicttype dicttype = userTask.getStatus();
			if(dicttype != null){
				status = dicttype.getTypename();
				statusID = dicttype.getId().toString();
			}
			userTaskMap.put("status", status==null?status="":status);//状态
			userTaskMap.put("statusID", statusID==null?statusID="":statusID);//状态ID
			Short signstatus = userTask.getSignstatus();
			userTaskMap.put("signstatus", signstatus==null?signstatus=2:signstatus);//签到状态
			String clientSigntime = "";
			Integer clientSigntimeInt =  userTask.getClientSigntime();
			if(clientSigntimeInt != null){
				clientSigntime = CommonUtil.integetTimeForString(clientSigntimeInt);
			}
			userTaskMap.put("clientSigntime", clientSigntime);//签到时间
//			String phoneNumber = userTask.getPhoneNumber();
//			userTaskMap.put("phoneNumber", phoneNumber==null?phoneNumber="":phoneNumber);//坐席号
//			String phonePassword = userTask.getPhonePassword();
//			userTaskMap.put("phonePassword", phonePassword==null?phonePassword="":phonePassword);//坐席号密码
//			String agentNumber = userTask.getAgentNumber();
//			userTaskMap.put("agentNumber", agentNumber==null?agentNumber="":agentNumber);//选线组号码
//			String agentPassword = userTask.getAgentPassword();
//			userTaskMap.put("agentPassword", agentPassword==null?agentPassword="":agentPassword);//选线组密码
			String createTime = "";
			Integer createTimeInt =  userTask.getCreateTime();
			if(createTimeInt != null){
				createTime = CommonUtil.integetTimeForString(createTimeInt);
			}
			userTaskMap.put("createTime", createTime);//创建时间
			String updateTime = "";
			Integer updateTimeInt =  userTask.getUpdateTime();
			if(updateTimeInt != null){
				updateTime = CommonUtil.integetTimeForString(updateTimeInt);
			}
			userTaskMap.put("updateTime",updateTime);//修改时间
			
			userTaskList.add(userTaskMap);
		}
		
        return userTaskList;
    }
    
    /**
     * 获取客服任务列表总条数
     * @param values
     * @return
     */
    public int getUserTaskListCount(Map<String ,Object> values){
    	
		logger.debug("获取客服任务列表总条数");
		
		String query = "select count(ut.id) from UserTask ut where 1=1 and ut.delStatus != '1'";
		
		//用户名
		String loginName = (String)values.get("loginName");
		if(loginName != null && !loginName.isEmpty()){
			query = query + " and ut.user.loginName like '%"+loginName+"%'";
		}
		
		//客服名称
		String name = (String)values.get("name");
		if(name != null && !name.isEmpty()){
			query = query + " and ut.user.name like '%"+name+"%'";
		}
		//任务名称
		String taskName = (String)values.get("taskName");
		if(taskName != null && !taskName.isEmpty()){
			query = query + " and ut.task.title like '%"+taskName+"%'";
		}
		//绑定手机号
		String bindPhone = (String)values.get("bindPhone");
		if(bindPhone != null && !bindPhone.isEmpty()){
			query = query + " and ut.bindPhone like '%"+bindPhone+"%'";
		}
		
		//状态
		String statusStr = (String)values.get("status");
		if(statusStr != null && !statusStr.isEmpty()){
			query = query + " and ut.status.id = "+statusStr;
		}
		//坐席号
		String phoneNumber = (String)values.get("phoneNumber");
		if(phoneNumber != null && !phoneNumber.isEmpty()){
			query = query + " and ut.phoneNumber like '%"+phoneNumber+"%'";
		}
		//操作员账号
		String agentNumber = (String)values.get("agentNumber");
		if(agentNumber != null && !agentNumber.isEmpty()){
			query = query + " and ut.agentNumber like '%"+agentNumber+"%'";
		}				
		int count = (int)(long)this.em.createQuery(query)
    			.getSingleResult();
		
        return count;
    }
    
    /**
     * 获取客服任务详情
     * @param userTaskID
     * @return
     */
    public Map<String ,Object> getUserTask(long userTaskID){
    	
		logger.debug("获取客服任务详情，任务id："+userTaskID);
		
		Map<String ,Object> userTaskMap = new HashMap<String, Object>();
		
		UserTask userTask = this.em.find(UserTask.class, userTaskID);
		
		String loginName = "";
		String nameStr = "";
		String phone = "";
		String sex = "";
		Integer age = 0;
		Short userStatus = 3;
		String address = "";
		String introduce = "";
		User user = userTask.getUser();
		if(user != null){
			loginName = user.getLoginName();
			nameStr = user.getName();
			phone = user.getStaffTel();
//			Short sexNum = user.getSex();
//			if(sexNum != null){
//				sex = ICommonConstants.GENDER.values()[sexNum].label();
//			}
			age = user.getAge();
			userStatus = user.getStatus();
			address = user.getCurAddress();
			introduce = user.getIntroduce();
		}
		userTaskMap.put("userID", user.getId().toString());//客服id
		userTaskMap.put("loginName", loginName==null?loginName="":loginName);//用户名
		userTaskMap.put("name", nameStr==null?nameStr="":nameStr);//姓名
		userTaskMap.put("phone", phone==null?phone="":phone);//手机号
		userTaskMap.put("sex", sex==null?sex="":sex);//性别
		userTaskMap.put("age", age==null?age=0:age);//年龄
		userTaskMap.put("userStatus", userStatus==null?userStatus=3:userStatus);//客服状态
		String bindPhoneStr = userTask.getBindPhone();
		userTaskMap.put("bindPhone", bindPhoneStr==null?bindPhoneStr="":bindPhoneStr);//绑定手机号
		userTaskMap.put("address", address==null?address="":address);//地址
		userTaskMap.put("introduce", introduce==null?introduce="":introduce);//简介
		String title = "";
		String desc = "";
		String entName = "";
		Short callTypeSh = 0;
		Double onlinePay = 0.0;
		Double callinPay = 0.0;
		Double calloutPay = 0.0;
		Double poPay = 0.0;
		Double money = 0.0;
		Integer csNeed = 0;
		Integer csHave = 0;
	    String taskStatus = "";
		Task task = userTask.getTask();
		if(task != null){
			title = task.getTitle();
			desc = task.getDesc();
			User user1 = task.getPubuser();
			if(user1 != null){
				entName = user1.getEntName();
			}
			callTypeSh = task.getCallType();
			onlinePay = task.getOnlinePay();
			callinPay = task.getCallinPay();
			calloutPay = task.getCalloutPay();
			poPay = task.getPoPay();
			TaskExtend taskExtend = task.getExtendIfo();
			if(taskExtend != null){
				money = taskExtend.getMoney();
				csNeed = taskExtend.getCsNeed();
				csHave = taskExtend.getCsHave();
			}
			Dicttype dicttype = task.getStatus();
			if(dicttype != null){
				taskStatus = dicttype.getTypename();
			}
		}
		userTaskMap.put("taskID", task.getId().toString());//任务id
		userTaskMap.put("title", title==null?title="":title);//任务名称
		userTaskMap.put("desc", desc==null?desc="":desc);//任务描述
		userTaskMap.put("entName", entName==null?entName="":entName);//发布企业
		userTaskMap.put("callType", callTypeSh==null?callTypeSh=0:callTypeSh);//任务呼叫类型
		userTaskMap.put("onlinePay", onlinePay==null?onlinePay=0.0:onlinePay);//在线时长报酬
		userTaskMap.put("callinPay", callinPay==null?callinPay=0.0:callinPay);//接听报酬
		userTaskMap.put("calloutPay", calloutPay==null?calloutPay=0.0:calloutPay);//外呼报酬
		userTaskMap.put("poPay", poPay==null?poPay=0.0:poPay);//成单报酬
		userTaskMap.put("money", money==null?money=0.0:money);//任务使用金额
		userTaskMap.put("csNeed", csNeed==null?csNeed=0:csNeed);//需要客服数量
		userTaskMap.put("csHave", csHave==null?csHave=0:csHave);//已招客服数量
		userTaskMap.put("taskStatus", taskStatus==null?taskStatus="":taskStatus);//任务状态
		String effectiveTime = "";
		Integer effectiveTimeInt = userTask.getEffectiveTime();
		if(effectiveTimeInt != null){
			effectiveTime = CommonUtil.integetTimeForString(effectiveTimeInt);
		}
		userTaskMap.put("effectiveTime", effectiveTime);//任务生效时间
		String status = "";
		String statusID = "";
		Dicttype dicttype = userTask.getStatus();
		if(dicttype != null){
			status = dicttype.getTypename();
			statusID = dicttype.getId().toString();
		}
		userTaskMap.put("status", status==null?status="":status);//状态
		userTaskMap.put("statusID", statusID==null?statusID="":statusID);//状态ID
		Short signstatus = userTask.getSignstatus();
		userTaskMap.put("signstatus", signstatus==null?signstatus=2:signstatus);//签到状态
		String clientSigntime = "";
		Integer clientSigntimeInt = userTask.getClientSigntime();
		if(clientSigntimeInt != null){
			clientSigntime = CommonUtil.integetTimeForString(clientSigntimeInt);
		}
		userTaskMap.put("clientSigntime", clientSigntime);//签到时间
		String createTime = "";
		Integer createTimeInt =  userTask.getCreateTime();
		if(createTimeInt != null){
			createTime = CommonUtil.integetTimeForString(createTimeInt);
		}
		userTaskMap.put("createTime", createTime);//创建时间
		String updateTime = "";
		Integer updateTimeInt =  userTask.getUpdateTime();
		if(updateTimeInt != null){
			updateTime = CommonUtil.integetTimeForString(updateTimeInt);
		}
		userTaskMap.put("updateTime",updateTime);//修改时间
		String remark = userTask.getRemark();
		userTaskMap.put("remark", remark==null?remark="":remark);//备注
		
		String phoneNumber = userTask.getPhoneNumber();// 坐席号(操作员)
	    String phonePassword = userTask.getPhonePassword();// 坐席号密码
	    String agentNumber = userTask.getAgentNumber();// 固话号（选线组号码）
	    String agentPassword = userTask.getAgentPassword();// 固话号密码
	    
	    userTaskMap.put("phoneNumber", phoneNumber==null?phoneNumber="":phoneNumber);
	    userTaskMap.put("phonePassword", phonePassword==null?phonePassword="":phonePassword);
	    userTaskMap.put("agentNumber", agentNumber==null?agentNumber="":agentNumber);
	    userTaskMap.put("agentPassword", agentPassword==null?agentPassword="":agentPassword);
		
        return userTaskMap;
    }
    
    /**
     * 获取客服操作信息
     * @param userTaskID
     * @return
     */
    public Map<String ,Object> getUserTaskPhoneNumAndAgentNuk(long userTaskID){
    	
		logger.debug("获取客服操作信息");
		
		UserTask userTask = this.em.find(UserTask.class, userTaskID);
		
		Map<String ,Object> userTaskMap = new HashMap<String, Object>();
		
		String phoneNumber = userTask.getPhoneNumber();
		userTaskMap.put("phoneNumber", phoneNumber==null?phoneNumber="":phoneNumber);//坐席号
		String phonePassword = userTask.getPhonePassword();
		userTaskMap.put("phonePassword", phonePassword==null?phonePassword="":phonePassword);//坐席号密码
		String agentNumber = userTask.getAgentNumber();
		userTaskMap.put("agentNumber", agentNumber==null?agentNumber="":agentNumber);//选线组号码
		String agentPassword = userTask.getAgentPassword();
		userTaskMap.put("agentPassword", agentPassword==null?agentPassword="":agentPassword);//选线组密码
		
		String ims = "";
		String imsPasswd = "";
		Task task = userTask.getTask();
		if(task != null){
			ImsPool imsPool = task.getImsPool();//总机号码
			if(imsPool != null){
				ims = imsPool.getIms();
				imsPasswd = imsPool.getImsPasswd();
			}
		}
		userTaskMap.put("ims", ims==null?ims="":ims);//总机号码
		userTaskMap.put("imsPasswd", imsPasswd==null?imsPasswd="":imsPasswd);//总机密码
		String bindPhone = userTask.getBindPhone();
		userTaskMap.put("bindPhone", bindPhone==null?bindPhone="":bindPhone);// 绑定的手机号
		
		return userTaskMap;
    }
    
    /**
     *  客服开通操作员
     * @return
     */
/*    @Transactional
    public UserTask updateUserTask(UserTask userTask){
    	
		logger.debug("客服开通操作员");
		
		String query = "update UserTask ut set ut.phoneNumber = ?1 , ut.phonePassword = ?2 , ut.agentNumber = ?3 ,ut.agentPassword = ?4 ,ut.updateTime = ?5 ,ut.status.id = 5 where ut.id = ?6";
		
		//修改任务状态
        this.em.createQuery(query)
                .setParameter(1, userTask.getPhoneNumber())
                .setParameter(2, userTask.getPhonePassword())
                .setParameter(3, userTask.getAgentNumber())
                .setParameter(4, userTask.getAgentPassword())
                .setParameter(5, CommonUtil.getCurrTimes())
                .setParameter(6, userTask.getId())
                .executeUpdate();
        dslJpaService.setEntityClass(UserTask.class);
        userTask = (UserTask) dslJpaService.findById(userTask.getId());
        //修改用户任务数
        User user = userTask.getUser();
        
        //更新applyWorktime运行状态
        int hour = new Date().getHours();
        this.em.createQuery("UPDATE ApplyWorktime as a  set a.runStatus = ?1 " +
                "where a.worktime = (from Worktime w where w.beginHour <= ?2 and w.endHour > ?2) and " +
                "a.userTask in (from UserTask u where u.task in (from Task t where t.runstatus = ?3))")
                .setParameter(1, (short) ICommonConstants.RUNSTATUS.HASBEGUN.ordinal())
                .setParameter(2,hour)
                .setParameter(3,(short) ICommonConstants.RUNSTATUS.HASBEGUN.ordinal())
                .executeUpdate();
        
        dataProcessService.updateUserExtendTaskNum(user);
        
		return userTask;
    }*/
    
}
